###### FROM the_grammar.R on http://had.co.nz/ggplot2 ########
## I've adapted this for the eye-tracking workshop -mcf

## install ggplot and load it
library(ggplot2)

#### qplot EXAMPLES WITH THE DIAMONDS DATASET #####

head(diamonds)

## scatter plots are trivial, and easy to add features to
qplot(diamonds$carat, diamonds$price)
qplot(carat, price, data = diamonds) # use the data frame 
qplot(carat, price, data = diamonds, colour=clarity)
qplot(carat, price, data = diamonds, colour=clarity, shape=cut)

## faceting is also really really easy
## the last plot was hard to read
qplot(carat, price, data = diamonds, 
      facets = cut ~ clarity) # x ~ y means row facets are by x, column facets by y

## QUESTION: facet only by cut, using . to indicate a missing argument. Do the 
## same by clarity.



## can use other geoms and manipulate their parameters
qplot(carat, data = diamonds,
  geom="histogram")
qplot(carat, data = diamonds,
  geom="histogram", binwidth = 1) 

## I hate the way the defaults look (though I'm getting slightly more used to
## them, so I always use theme_bw()
qplot(carat, data = diamonds,
      geom="histogram")

## with theme_bw()
qplot(carat, data = diamonds,
      geom="histogram") + theme_bw() 

## QUESTION: try making a faceted histogram by clarity and/or cut!



#### ggplot EXAMPLES WITH THE DIAMONDS DATASET #####
## ggplot is just a way of building qplot calls up more systematically. it's
## sometimes easier to use and sometimes a bit more complicated. 

d <- ggplot(diamonds, aes(x=carat, y=price)) # first you set the aesthetic and dataset
d + geom_point() # then you add geoms
d + geom_point(aes(colour = carat)) # and you can keep doing this to add layers to the plot


## you can also set the aesthetic separately for each geom, though this can get
## complicated!
ggplot(diamonds) + geom_histogram(aes(x=price))

## sometimes using ggplot is best when you want to add different statistics
p <- ggplot(diamonds, aes(x=price))

p + geom_histogram()
p + stat_bin(geom="area")
p + stat_bin(geom="point")
p + stat_bin(geom="line")

p + geom_histogram(aes(fill = clarity))

## QUESTION: can you make the faceted histogram from before, building it using 
## ggplot and facet_grid? (google or look at help on facet_grid).


